package top.kaoshanji.p3ch11b;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.concurrent.Exchanger;

/**
 * 代码清单-p3ch11b-362页a：对象交换器的使用示例
 * author kaoshanji
 * ^_^
 * create time 2025/2/5 10:21
 */
public class SendAndReceiver {

    private static final Logger logger = LogManager.getLogger(SendAndReceiver.class);

    public static void main(String[] args) {
        logger.info("...代码清单-p3ch11b-362页a：对象交换器的使用示例...");

        SendAndReceiver prog = new SendAndReceiver();
        prog.exchange();

    }

    private final Exchanger<StringBuilder> exchanger = new Exchanger<>();

    public void exchange() {

        new Thread(new Sender()).start();
        new Thread(new Receiver()).start();

    }

    private class Sender implements Runnable {

        @Override
        public void run() {

            try {
                StringBuilder content = new StringBuilder("Hello");
                content = exchanger.exchange(content);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }
    }

    private class Receiver implements Runnable {

        @Override
        public void run() {

            try {
                StringBuilder content = new StringBuilder("World");
                content = exchanger.exchange(content);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }
    }


}
